package org.x.common.web.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.x.common.base.util.UserContextHolder;

import java.io.IOException;


@Component
public class UserRequestFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 从Header解析信息
        String tenantId = request.getHeader("X-Tenant-Id");
        String userId = request.getHeader("X-User-Id");
        String userName = request.getHeader("X-User-Name");
        String roles = request.getHeader("X-User-Roles");

        if (StringUtils.isNotEmpty(tenantId)) {
            UserContextHolder.setTenantId(tenantId);
        }
        if (StringUtils.isNotEmpty(userId)) {
            UserContextHolder.setUserId(userId);
        }
        if (StringUtils.isNotEmpty(userName)) {
            UserContextHolder.setUserName(userName);
        }
        if (StringUtils.isNotEmpty(roles)) {
            UserContextHolder.put("roles", roles);
        }

        filterChain.doFilter(request, response);
    }


}